from django.contrib.auth.backends import ModelBackend
from re import match
from .models import User
from itsdangerous import TimedJSONWebSignatureSerializer as tjwss, BadData
from django.conf import settings


def get_user_by_account(account):
    try:
        if match('^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except Exception as e:
        return None
    else:
        return user


class UsernameMobileBackend(ModelBackend):
    def authenticate(self, request, username = None, password = None, **kwargs):
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user


def generate_email_verify_url(user):
    _tjwss = tjwss(secret_key = settings.SECRET_KEY, expires_in = 3600)
    data = {'user_id': user.id, 'email': user.email}
    token = _tjwss.dumps(data).decode()
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url


def get_user_token(token):
    _tjwss = tjwss(secret_key = settings.SECRET_KEY, expires_in = 3600)
    try:
        data = _tjwss.loads(token)
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id = user_id, email = email)
            return user
        except User.DoesNotExist:
            return None
    except BadData:
        return None